import os
import requests
import re
from tqdm import tqdm
import zipfile

ac_id = input('请输入你要下载的视频ID:')

url = f'https://www.acfun.cn/v/{ac_id}'

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}

resp = requests.get(url, headers=headers)

# print(resp.text)

# 获取视频的标题
title = re.findall('<span>(.*?)</span>', resp.text)[0]
print(title)

# 获取 m3u8 url地址
m3u8_url = re.findall('backupUrl(.*?)\"]', resp.text)[0].replace('"', '').split('\\')[2]
# print(m3u8_url)

# 下载m3u8
m3u8_data = requests.get(url=m3u8_url, headers=headers).text

# 处理m3u8文件
m3u8_data = re.sub('#EXTM3U', '', m3u8_data)
m3u8_data = re.sub('#EXT-X-VERSION:\d', '', m3u8_data)
m3u8_data = re.sub('#EXT-X-TARGETDURATION:\d+', '', m3u8_data)
m3u8_data = re.sub('#EXT-X-MEDIA-SEQUENCE:\d', '', m3u8_data)
m3u8_data = re.sub('#EXTINF:\d\.\d+,', '', m3u8_data)
m3u8_data = re.sub('#EXT-X-ENDLIST', '', m3u8_data)
# print(m3u8_data)

m3u8_data_list = m3u8_data.split()
print(m3u8_data_list)

# 创建以视频名字命名的文件夹
filename = f'{title}\\'
if not os.path.exists(filename):
    os.mkdir(filename)

# 下载ts文件
print('正在开始下载ts文件，请稍后......')

pre_url = 'https://tx-safety-video.acfun.cn/mediacloud/acfun/acfun_video/'

# tqdm实际上是一个进度条，用于显示下载进度
files = os.listdir(filename)
if len(files) == 0:
    for item in tqdm(m3u8_data_list):
        link_url = pre_url + item
        link_name = item.split('.')[1]
        link_content = requests.get(url=link_url, headers=headers).content

        with open(filename + link_name + '.ts', mode='wb') as f:
            f.write(link_content)

print('ts 视频下载完成!!!!!!')

print('开始视频片段合成..................')
files = os.listdir(filename)
with zipfile.ZipFile(filename + title + '.mp4', mode='w') as z:
    for file in tqdm(files):
        ts_content = filename + file
        z.write(ts_content)
        os.remove(ts_content)

print('视频片段合并完成！！！！！！！！！！！！！')



